package com.lfy.yunpicture.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lfy.yunpicture.common.ErrorCode;
import com.lfy.yunpicture.constant.CommonConstant;
import com.lfy.yunpicture.exception.ThrowUtils;
import com.lfy.yunpicture.mapper.SpaceUserMapper;
import com.lfy.yunpicture.model.dto.spaceuser.SpaceUserQueryRequest;
import com.lfy.yunpicture.model.entity.Space;
import com.lfy.yunpicture.model.entity.SpaceUser;
import com.lfy.yunpicture.model.entity.User;
import com.lfy.yunpicture.model.enums.SpaceRoleEnum;
import com.lfy.yunpicture.model.vo.SpaceUserVO;
import com.lfy.yunpicture.model.vo.UserVO;
import com.lfy.yunpicture.service.SpaceService;
import com.lfy.yunpicture.service.SpaceUserService;
import com.lfy.yunpicture.service.UserService;
import com.lfy.yunpicture.utils.SqlUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 团队空间成员服务实现
 *
*/
@Service
@Slf4j
public class SpaceUserServiceImpl extends ServiceImpl<SpaceUserMapper, SpaceUser> implements SpaceUserService {

    @Resource
    private UserService userService;
    @Resource
    private SpaceService spaceService;
    /**
     * 校验数据
     *
     * @param spaceUser
     * @param add      对创建的数据进行校验
     */
    @Override
    public void validSpaceUser(SpaceUser spaceUser, boolean add) {
        ThrowUtils.throwIf(spaceUser == null, ErrorCode.PARAMS_ERROR);
        // 从对象中取值
        String spaceRole = spaceUser.getSpaceRole();
        Long spaceId = spaceUser.getSpaceId();
        Long userId = spaceUser.getUserId();
        // 创建数据时，参数不能为空
        if (add) {
            // 补充校验规则
            ThrowUtils.throwIf(spaceRole == null, ErrorCode.PARAMS_ERROR);
            ThrowUtils.throwIf(spaceId == null || spaceId <= 0, ErrorCode.PARAMS_ERROR);
            ThrowUtils.throwIf(userId == null || userId <= 0, ErrorCode.PARAMS_ERROR);
            Space space = spaceService.getById(spaceId);
            ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR,"空间不存在");
            User user = userService.getById(userId);
            ThrowUtils.throwIf(user == null, ErrorCode.NOT_FOUND_ERROR, "用户不存在");
        }
        // 修改数据时，有参数则校验
        // 补充校验规则
        ThrowUtils.throwIf(SpaceRoleEnum.getEnumByValue(spaceRole) == null,ErrorCode.PARAMS_ERROR,"空间权限不存在");
    }

    /**
     * 获取查询条件
     *
     * @param spaceUserQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<SpaceUser> getQueryWrapper(SpaceUserQueryRequest spaceUserQueryRequest) {
        QueryWrapper<SpaceUser> queryWrapper = new QueryWrapper<>();
        if (spaceUserQueryRequest == null) {
            return queryWrapper;
        }
        // 从对象中取值
        Long id = spaceUserQueryRequest.getId();
        Long spaceId = spaceUserQueryRequest.getSpaceId();
        Long userId = spaceUserQueryRequest.getUserId();
        String spaceRole = spaceUserQueryRequest.getSpaceRole();
        String sortField = spaceUserQueryRequest.getSortField();
        String sortOrder = spaceUserQueryRequest.getSortOrder();

        // 补充需要的查询条件
        // 精确查询
        queryWrapper.eq(ObjectUtils.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "userId", userId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(spaceId), "spaceId", spaceId);
        queryWrapper.eq(StrUtil.isNotBlank(spaceRole), "spaceRole", spaceRole);
        // 排序规则
        queryWrapper.orderBy(SqlUtils.validSortField(sortField),
                sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }

    /**
     * 获取团队空间成员封装
     *
     * @param spaceUser
     * @param request
     * @return
     */
    @Override
    public SpaceUserVO getSpaceUserVO(SpaceUser spaceUser, HttpServletRequest request) {
        // 对象转封装类
        SpaceUserVO spaceUserVO = SpaceUserVO.objToVo(spaceUser);
        //可以根据需要为封装对象补充值，不需要的内容可以删除
        // region 可选
        // 1. 关联查询用户信息
        Long userId = spaceUser.getUserId();
        User user = null;
        if (userId != null && userId > 0) {
            user = userService.getById(userId);
        }
        UserVO userVO = userService.getUserVO(user);
        spaceUserVO.setUser(userVO);
        // endregion
        return spaceUserVO;
    }

    /**
     * 分页获取团队空间成员封装
     *
     * @param spaceUserPage
     * @param request
     * @return
     */
    @Override
    public Page<SpaceUserVO> getSpaceUserVOPage(Page<SpaceUser> spaceUserPage, HttpServletRequest request) {
        List<SpaceUser> spaceUserList = spaceUserPage.getRecords();
        Page<SpaceUserVO> spaceUserVOPage = new Page<>(spaceUserPage.getCurrent(), spaceUserPage.getSize(), spaceUserPage.getTotal());
        if (CollUtil.isEmpty(spaceUserList)) {
            return spaceUserVOPage;
        }
        // 对象列表 => 封装对象列表
        List<SpaceUserVO> spaceUserVOList = spaceUserList.stream().map(spaceUser -> {
            return SpaceUserVO.objToVo(spaceUser);
        }).collect(Collectors.toList());

        // 可以根据需要为封装对象补充值，不需要的内容可以删除
        // region 可选
        // 1. 关联查询用户信息
        Set<Long> userIdSet = spaceUserList.stream().map(SpaceUser::getUserId).collect(Collectors.toSet());
        Map<Long, List<User>> userIdUserListMap = userService.listByIds(userIdSet).stream()
                .collect(Collectors.groupingBy(User::getId));
        // 填充信息
        spaceUserVOList.forEach(spaceUserVO -> {
            Long userId = spaceUserVO.getUserId();
            User user = null;
            if (userIdUserListMap.containsKey(userId)) {
                user = userIdUserListMap.get(userId).get(0);
            }
            spaceUserVO.setUser(userService.getUserVO(user));
            });
        // endregion
        spaceUserVOPage.setRecords(spaceUserVOList);
        return spaceUserVOPage;
    }

}
